<?php

namespace App\Exceptions;

use Exception;
use App\Support\Code;
use Illuminate\Validation\ValidationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        ConfigNotSetException::class,
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    public function render($request, Exception $exception)
    {
        if (app()->environment() == 'local') {
            return parent::render($request, $exception);
        }

        if ($request->is('api/*')) {
            $result = ['data' => '', 'code' => Code::PARAMETER_ERROR];
            if (app()->environment() !== 'production') {
                $result['request'] = request()->all();
            }
            if ($exception instanceof ValidationException) {
                $result['msg'] = implode(
                    "\n",
                    array_merge(...array_values($exception->errors()))
                );
                return response()->json($result);
            } else {
                $result['msg'] = $exception->getMessage();
                return response()->json($result);
            }
        }
        return parent::render($request, $exception);
    }
}
